package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 扣减库存处理
 * @author Javid Xi
 * @version 1.0
 * @since 2021/7/20
 */
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

	@Autowired
	private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	/**
	 * 库存处理
	 * @param context 上下文
	 * @return boolean
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean handle(TransHandlerContext context) {
		CreateOrderContext orderContext= (CreateOrderContext) context;
		List<CartProductDto> cartProductDtos = orderContext.getCartProductDtoList();
		List<Long> buyProductIds = orderContext.getBuyProductIds();

		if(CollectionUtils.isEmpty(buyProductIds)){
			buyProductIds = cartProductDtos.stream().map(CartProductDto::getProductId).collect(Collectors.toList());
		}
		buyProductIds.sort(Long::compareTo);

		// 锁定库存
		List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);
		if(CollectionUtils.isEmpty(stockList)) {
			throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),"商品库存未初始化");
		}
		if(stockList.size() != buyProductIds.size()) {
			throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), "有商品未初始化库存,请在如下商品id中检查库存状态：" + buyProductIds);
		}

		for (CartProductDto productDto : cartProductDtos) {
			Long productId = productDto.getProductId();
			Long productNum = productDto.getProductNum();

			// 购买数量不能大于 limit
			Example stockExample = new Example(Stock.class);
			stockExample.createCriteria().andEqualTo("itemId", productId);
			Stock stock = stockMapper.selectOneByExample(stockExample);
			if(productNum > stock.getRestrictCount()){
				throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),"购买数量超过限制");
			}

			Stock newStock = new Stock();
			newStock.setItemId(productId);
			newStock.setLockCount(productNum.intValue());
			newStock.setStockCount(-productNum);
			// 更新库存
			stockMapper.updateStock(newStock);
		}
		return true;
	}
}